<template>
  <MainContent title="商家管理">
    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="商家名称">
            <el-input
              v-model.trim="tableForm.storeName"
              clearable
              placeholder="请输入商家名称"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="tableForm.status"
              class="m-2"
              placeholder="请选择状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="onSearch"
            >
              查询
            </el-button>

            <el-button
              v-has="['130201']"
              type="primary"
              @click="dialogData.showDialog = true"
            >
              新建商家
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>
    <LayoutTable
      ref="integralModel"
      url="/merchant/store/pageStore"
      :set-search="setSearch"
      disable-auto-height
      :param="tableForm"
    >
      <el-table-column
        prop="storeName"
        label="商家名称"
        min-width="200"
      />
      <el-table-column
        prop="userName"
        label="用户名"
        min-width="120"
      />
      <el-table-column
        prop="configName"
        label="供应商配置"
        min-width="120"
      />
      <el-table-column
        prop="number"
        label="商品数量"
        min-width="100"
      />
      <el-table-column
        prop="status"
        label="状态"
        min-width="100"
      >
        <template #default="scope">
          <el-switch
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @click="setStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="余额扣款"
        min-width="150"
      >
        <template #default="scope">
          <div style="display: flex;align-items: center;"> 
            <el-switch
              v-if="scope.row.deductCheckStatus==0"
              v-model="scope.row.deductStatus"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="开启"
              inactive-text="关闭"
              :before-change="()=>changeDeductStatus(scope.row)"
            />
            <el-switch
              v-if="scope.row.deductCheckStatus==1"
              v-model="scope.row.deductStatus"
              :active-value="1"
              :inactive-value="0"
              active-color="#0052d9"
              inactive-color="#0052d9"
              inline-prompt
              active-text="待审核"
              inactive-text="待审核"
              :before-change="()=>changeDeductStatus(scope.row)"
            />
            <el-popover
              v-if="scope.row.applyRemark"
              placement="top-start"
              title="原因:"
              :content="scope.row.applyRemark"
              trigger="hover"
            >
              <template #reference>
                <el-icon style="margin-left: 10px;font-size: 14px;">
                  <ChatLineSquare />
                </el-icon>
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="180"
      >
        <template #default="scope">
          {{ dateFormat(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column
        v-has="['130202', '130204']"
        label="操作"
        width="150"
      >
        <template #default="scope">
          <div>
            <el-button
              v-has="['130202']"
              type="primary"
              link
              @click="toEditor(scope.row)"
            >
              编辑
            </el-button>
            <!-- <el-button @click="merchantConfig(scope.row)" type="primary" link v-has="['130203']">配置</el-button> -->
            <el-button
              v-has="['130204']"
              type="primary"
              link
              @click="toSetPassword(scope.row)"
            >
              修改密码
            </el-button>
            <!--            <el-button @click="delBusinesConfirm(scope.row)" type="danger" link>删除</el-button>-->
          </div>
        </template>
      </el-table-column>
    </LayoutTable>
  </MainContent>

  <Add-Busines
    :show-dialog="dialogData.showDialog"
    :model-data="modelData"
    @confirm="confirm"
    @cancel="cancel"
  />
  <Set-Password
    :show-dialog="dialogData.showPassWordDialog"
    :model-data="modelData"
    @confirm="confirm"
    @cancel="cancel"
  />
  <!-- <Merchant-Configuration :showDialog="dialogData.showMerchantDialog" :modelData="modelData" @confirm="confirm" @cancel="cancel"></Merchant-Configuration> -->
</template>
<script lang="ts">
export default {
  name: 'BusinesManagement'
}
</script>
<script lang="ts" setup>
import AddBusines from './components/addBusines.vue'
import SetPassword from './components/setPassword.vue'
// import MerchantConfiguration from './components/merchantConfiguration.vue'
import { dateFormat } from "@/utils/filters";

import {
  delBusinesManagement,
  setBusinesManagementStatus,
  updDeductStatus
} from "@/api/product";

const tableForm = ref({
  storeName: "",
  status: null,
});

const userId = ref('')
const integralModel = ref();
const modelData = ref({ id: null, name: '' })
const statusList = ref([
  { id: null, name: "全部" },
  { id: 1, name: "启用" },
  { id: 0, name: "停用" },
]);


const dialogData = ref({
  showDialog: false,
  showPassWordDialog: false,
  // showMerchantDialog: false,
})
const setSearch = ref(Number());
const setStatus = (row: any) => {
  ElMessageBox.confirm("是否修改状态?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log('enter', row)
      customerUpdateStatus(row);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const changeDeductStatus = (row: any) => {
  console.log(row)
  return new Promise((resolve, reject) => {
    if (row.deductStatus == 0 && row.deductCheckStatus == 0){
      ElMessageBox.confirm('开启商户余额扣款,需saas管理员审核,避免造成资金结算异常', '开启余额扣款', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(()=>{
          updateDeductStatus(row);
          return resolve(false)
      }).catch(()=>{
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
        return resolve(false)
      })
    } else if (row.deductStatus == 0 && row.deductCheckStatus == 1){
      ElMessageBox.confirm('您申请的开启余额扣款正在审核中,请耐心等待~', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(()=>{
          return resolve(false)
      }).catch(()=>{
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
        return resolve(false)
      })

    } else if (row.deductStatus == 1 && row.deductCheckStatus == 1){
      ElMessageBox.confirm('您申请的关闭余额扣款正在审核中,请耐心等待~', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(()=>{
        return resolve(false)
      }).catch(()=>{
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
        return resolve(false)
      })
    } else {
      ElMessageBox.confirm("关闭商户余额扣款,需saas管理员审核,避免造成资金结算异常", "关闭余额扣款", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateDeductStatus(row);
          return resolve(false)
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消操作",
          });
          return resolve(false)
        });
    }
  })
}
const updateDeductStatus = async(row:any) => {
  const rs = await updDeductStatus({
    id: row.id,
    name: row.storeName
  });
  if (rs.code == 200) {
    ElMessage.success('已提交审核')
    onSearch()
  } 
}
const delBusinesConfirm = (row: any) => {
  ElMessageBox.confirm("是否删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delBusines(row);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const delBusines = async (row: any) => {
  let rs: any = await delBusinesManagement({ id: row.id, name: row.storeName });
  if (rs.code === 200) {
    ElMessage.success('删除成功')
    onSearch()
  }
}


const toEditor = (row: any) => {
  modelData.value = row
  dialogData.value.showDialog = true
}

// 修改密码
const toSetPassword = (row: any) => {
  modelData.value = row
  dialogData.value.showPassWordDialog = true
}

// // 配置
// const merchantConfig = (row: any)=> {
//   modelData.value = row
//   dialogData.value.showMerchantDialog = true
// }


const customerUpdateStatus = async (row: any) => {
  let rs: any = await setBusinesManagementStatus({ id: row.id, name: row.storeName });
  if (rs.code === 200) {
    ElMessage.success('状态修改成功')
    onSearch()
  }
}
const openAwarded = (row: any) => {
  dialogData.value.showDialog = true
  userId.value = row.userId
}

const confirm = () => {
  onSearch();
};
const cancel = (dialogType: any) => {
  dialogData.value[dialogType] = false;
  modelData.value = { id: null, name: '' }
};

const onSearch = () => {
  setSearch.value++;
};

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    onSearch();
  },
  {
    deep: true
  }
)
</script>

<style lang="scss" scoped></style>
